/**
 * 云链方舟插件检测脚本 - TypeScript版本
 * 使用DOM注入方式检测插件，更可靠
 * 
 * 功能封装：
 * 1. 插件检测 - 检测云链方舟插件是否安装
 * 2. Cookie获取 - 从登录页面自动获取cookies
 * 3. 事件监听 - 监听插件检测结果
 * 4. 错误处理 - 完善的错误处理和重试机制
 */

// 类型定义
interface PluginInfo {
    isInstalled: boolean;
    version: string | null;
    pluginName: string;
    timestamp: number;
    userAgent: string;
    extensionId?: string;
}

interface DetectionResult {
    isInstalled: boolean;
    version: string | null;
    extensionId?: string;
}

interface CookiesResponse {
    success: boolean;
    cookies?: string;
    error?: string;
    message?: string;
}

interface PlatformConfig {
    name: string;
    loginUrl: string;
    cookieDomain: string;
}

interface AddShopResult {
    success: boolean;
    data?: any;
    error?: string;
    message?: string;
}

interface AddShopFunction {
    (shopType: number, cookies: string): Promise<AddShopResult>;
}

interface YunLianFangZhouDetector {
    isInstalled: boolean;
    version: string | null;
    extensionId: string | undefined;
    detect(): Promise<boolean>;
    detectWithExtensionId(): Promise<boolean>;
    getInfo(): PluginInfo;
    getCookiesFromLogin(loginUrl: string, cookieDomain: string): Promise<string>;
    addShop(shopType: number, platformConfig: PlatformConfig, addShopFn: AddShopFunction): Promise<AddShopResult>;
    addShopByType(shopType: number, addShopFn: AddShopFunction): Promise<AddShopResult>;
    onDetected(callback: (info: PluginInfo) => void): void;
    removeDetectedListener(callback: (info: PluginInfo) => void): void;
}

// 全局声明
declare global {
    interface Window {
        YunLianFangZhou: YunLianFangZhouDetector;
        chrome: any;
    }
    
    const chrome: any;
}

// 插件配置
const PLUGIN_NAME = '云链方舟插件';
const DETECTION_ELEMENT_ID = 'yunlianfangzhou-detection';

// 预定义平台配置
const PLATFORM_CONFIGS: Record<number, PlatformConfig> = {
    1: {
        name: '美团',
        loginUrl: 'https://e.waimai.meituan.com/login',
        cookieDomain: 'e.waimai.meituan.com'
    },
    2: {
        name: '饿了么',
        loginUrl: 'https://melody.shop.ele.me/app/shop/1293360190/dashboard#app.shop.dashboard',
        cookieDomain: 'melody.shop.ele.me'
    },
    3: {
        name: '京东到家',
        loginUrl: 'https://store.jddj.com/login',
        cookieDomain: 'store.jddj.com'
    }
};

// 检测器类
class YunLianFangZhouDetectorImpl implements YunLianFangZhouDetector {
    public isInstalled: boolean = false;
    public version: string | null = null;
    public extensionId: string | undefined = undefined;
    private detectedCallbacks: Array<(info: PluginInfo) => void> = [];

    /**
     * 检测插件是否安装
     * @returns {Promise<boolean>} 检测结果
     */
    public detect(): Promise<boolean> {
        return new Promise<boolean>((resolve) => {
            // 注入检测元素
            this._injectDetectionElement();
            
            // 等待插件响应
            this._waitForPluginResponse()
                .then((result: DetectionResult) => {
                    this.isInstalled = result.isInstalled;
                    this.version = result.version;
                    this.extensionId = result.extensionId;
                    resolve(this.isInstalled);
                })
                .catch(() => {
                    this.isInstalled = false;
                    resolve(false);
                });
        });
    }

    /**
     * 注入检测元素
     * @private
     */
    private _injectDetectionElement(): void {
        // 移除之前的检测元素
        const existingElement = document.getElementById(DETECTION_ELEMENT_ID);
        if (existingElement) {
            existingElement.remove();
        }
        
        // 创建新的检测元素
        const detectionDiv = document.createElement('div');
        detectionDiv.id = DETECTION_ELEMENT_ID;
        detectionDiv.style.display = 'none';
        detectionDiv.setAttribute('data-plugin-name', PLUGIN_NAME);
        detectionDiv.setAttribute('data-timestamp', Date.now().toString());
        document.body.appendChild(detectionDiv);
        
        console.log('已注入检测元素，等待插件响应...');
    }

    /**
     * 注入检测元素（请求扩展ID）
     * @private
     */
    private _injectDetectionElementWithExtensionId(): void {
        // 移除之前的检测元素
        const existingElement = document.getElementById(DETECTION_ELEMENT_ID);
        if (existingElement) {
            existingElement.remove();
        }
        
        // 创建新的检测元素
        const detectionDiv = document.createElement('div');
        detectionDiv.id = DETECTION_ELEMENT_ID;
        detectionDiv.style.display = 'none';
        detectionDiv.setAttribute('data-plugin-name', PLUGIN_NAME);
        detectionDiv.setAttribute('data-timestamp', Date.now().toString());
        detectionDiv.setAttribute('data-request-extension-id', 'true');
        document.body.appendChild(detectionDiv);
        
        console.log('已注入检测元素（请求扩展ID），等待插件响应...');
    }

    /**
     * 等待插件响应
     * @private
     */
    private _waitForPluginResponse(): Promise<DetectionResult> {
        return new Promise<DetectionResult>((resolve) => {
            const startTime = Date.now();
            const timeout = 5000; // 5秒超时
            
            const checkInterval = setInterval(() => {
                const element = document.getElementById(DETECTION_ELEMENT_ID);
                
                if (element) {
                    const detected = element.getAttribute('data-detected');
                    const version = element.getAttribute('data-version');
                    const extensionId = element.getAttribute('data-extension-id');
                    
                    if (detected === 'true') {
                        clearInterval(checkInterval);
                        console.log('插件检测成功！版本:', version, '扩展ID:', extensionId);
                        resolve({
                            isInstalled: true,
                            version: version || '1.0.0',
                            extensionId: extensionId || undefined
                        });
                        return;
                    }
                }
                
                // 检查超时
                if (Date.now() - startTime > timeout) {
                    clearInterval(checkInterval);
                    console.log('插件检测超时，尝试重新注入检测元素...');
                    
                    // 超时后尝试重新注入检测元素
                    this._injectDetectionElement();
                    
                    // 再等待2秒
                    setTimeout(() => {
                        const retryElement = document.getElementById(DETECTION_ELEMENT_ID);
                        if (retryElement && retryElement.getAttribute('data-detected') === 'true') {
                            const version = retryElement.getAttribute('data-version');
                            const extensionId = retryElement.getAttribute('data-extension-id');
                            console.log('重试检测成功！版本:', version, '扩展ID:', extensionId);
                            resolve({
                                isInstalled: true,
                                version: version || '1.0.0',
                                extensionId: extensionId || undefined
                            });
                        } else {
                            console.log('重试检测仍然失败');
                            resolve({ isInstalled: false, version: null, extensionId: undefined });
                        }
                    }, 2000);
                }
            }, 100);
        });
    }

    /**
     * 检测插件是否安装（包含扩展ID）
     * @returns {Promise<boolean>} 检测结果
     */
    public detectWithExtensionId(): Promise<boolean> {
        return new Promise<boolean>((resolve) => {
            // 注入检测元素（请求扩展ID）
            this._injectDetectionElementWithExtensionId();
            
            // 等待插件响应
            this._waitForPluginResponse()
                .then((result: DetectionResult) => {
                    this.isInstalled = result.isInstalled;
                    this.version = result.version;
                    this.extensionId = result.extensionId;
                    resolve(this.isInstalled);
                })
                .catch(() => {
                    this.isInstalled = false;
                    resolve(false);
                });
        });
    }

    /**
     * 获取插件信息
     * @returns {PluginInfo} 插件信息
     */
    public getInfo(): PluginInfo {
        return {
            isInstalled: this.isInstalled,
            version: this.version,
            pluginName: PLUGIN_NAME,
            timestamp: Date.now(),
            userAgent: navigator.userAgent,
            extensionId: this.extensionId
        };
    }

    /**
     * 从登录页面获取cookies
     * @param {string} loginUrl 登录页面URL
     * @param {string} cookieDomain Cookie域名
     * @returns {Promise<string>} 返回cookies字符串
     */
    public getCookiesFromLogin(loginUrl: string, cookieDomain: string): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            // 检查插件是否安装
            if (!this.isInstalled) {
                reject(new Error('云链方舟插件未安装'));
                return;
            }

            // 检查扩展ID是否可用
            if (!this.extensionId) {
                reject(new Error('无法获取插件扩展ID，请重新检测插件'));
                return;
            }

            // 获取浏览器扩展API（支持Chrome和Edge）
            const extensionAPI = this._getExtensionAPI();
            if (!extensionAPI) {
                reject(new Error('浏览器扩展API不可用'));
                return;
            }

            console.log('Web端使用扩展API: chrome');
            console.log('目标扩展ID:', this.extensionId);
            console.log('扩展ID类型:', typeof this.extensionId);
            console.log('扩展ID长度:', this.extensionId ? this.extensionId.length : 'undefined');
            console.log('发送消息到插件:', {
                action: 'getCookiesFromLogin',
                login_url: loginUrl,
                cookie_domain: cookieDomain
            });

            // 发送获取cookies请求（Web页面必须提供扩展ID）
            console.log('准备调用 sendMessage，参数:', this.extensionId, {
                action: 'getCookiesFromLogin',
                login_url: loginUrl,
                cookie_domain: cookieDomain
            });
            
            // 确保扩展ID是字符串类型
            const extensionIdString = String(this.extensionId);
            console.log('转换后的扩展ID:', extensionIdString, '类型:', typeof extensionIdString);
            
            extensionAPI.runtime.sendMessage(extensionIdString, {
                action: 'getCookiesFromLogin',
                login_url: loginUrl,
                cookie_domain: cookieDomain
            }, (response: CookiesResponse) => {
                if (extensionAPI.runtime.lastError) {
                    console.error('插件通信错误:', extensionAPI.runtime.lastError);
                    reject(new Error(`插件通信错误: ${extensionAPI.runtime.lastError.message}`));
                } else if (response && response.success) {
                    resolve(response.cookies || '');
                } else {
                    console.error('插件授权失败:', response);
                    reject(new Error(response ? response.error || '获取cookies失败' : '插件未正确响应,请检查插件是否支持getCookiesFromLogin功能'));
                }
            });
        });
    }

    /**
     * 获取浏览器扩展API（Web页面只能使用chrome API）
     * @private
     */
    private _getExtensionAPI(): any {
        // Web页面只能使用chrome API，browser API只在扩展内部可用
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            return chrome;
        }
        return null;
    }

    /**
     * 添加店铺 - 完整的业务流程封装
     * @param {number} shopType 店铺类型
     * @param {PlatformConfig} platformConfig 平台配置
     * @param {AddShopFunction} addShopFn 外部传入的添加店铺函数
     * @returns {Promise<AddShopResult>} 添加结果
     */
    public async addShop(shopType: number, platformConfig: PlatformConfig, addShopFn: AddShopFunction): Promise<AddShopResult> {
        try {
            console.log(`开始添加${platformConfig.name}店铺...`);
            
            // 1. 检测插件是否安装
            if (!this.isInstalled) {
                const detected = await this.detect();
                if (!detected) {
                    throw new Error('请先安装云链方舟插件');
                }
            }
            
            // 2. 通过插件获取cookies
            console.log('正在打开登录页面...');
            const cookies = await this.getCookiesFromLogin(
                platformConfig.loginUrl,
                platformConfig.cookieDomain
            );
            
            console.log('获取到cookies:', cookies);
            
            // 3. 调用外部传入的添加店铺函数
            console.log('正在调用添加店铺API...');
            const result = await addShopFn(shopType, cookies);
            
            if (result.success) {
                console.log('店铺添加成功:', result);
                return {
                    success: true,
                    data: result.data,
                    message: `${platformConfig.name}店铺添加成功`
                };
            } else {
                throw new Error(result.error || '添加店铺失败');
            }
            
        } catch (error) {
            console.error('添加店铺失败:', error);
            return {
                success: false,
                error: error instanceof Error ? error.message : '未知错误',
                message: '添加店铺失败'
            };
        }
    }

    /**
     * 使用预定义配置添加店铺
     * @param {number} shopType 店铺类型（1:美团, 2:饿了么, 3:京东到家）
     * @param {AddShopFunction} addShopFn 外部传入的添加店铺函数
     * @returns {Promise<AddShopResult>} 添加结果
     */
    public async addShopByType(shopType: number, addShopFn: AddShopFunction): Promise<AddShopResult> {
        const platformConfig = PLATFORM_CONFIGS[shopType];
        if (!platformConfig) {
            return {
                success: false,
                error: `不支持的店铺类型: ${shopType}`,
                message: '添加店铺失败'
            };
        }
        
        return this.addShop(shopType, platformConfig, addShopFn);
    }

    /**
     * 监听插件检测事件
     * @param {Function} callback 回调函数
     */
    public onDetected(callback: (info: PluginInfo) => void): void {
        this.detectedCallbacks.push(callback);
    }

    /**
     * 移除插件检测事件监听器
     * @param {Function} callback 回调函数
     */
    public removeDetectedListener(callback: (info: PluginInfo) => void): void {
        const index = this.detectedCallbacks.indexOf(callback);
        if (index > -1) {
            this.detectedCallbacks.splice(index, 1);
        }
    }

    /**
     * 触发检测事件
     * @private
     */
    private triggerDetectedEvent(): void {
        const info = this.getInfo();
        this.detectedCallbacks.forEach(callback => {
            try {
                callback(info);
            } catch (error) {
                console.error('检测事件回调执行失败:', error);
            }
        });
    }

    /**
     * 获取预定义平台配置
     * @returns {Record<number, PlatformConfig>} 平台配置
     */
    public static getPlatformConfigs(): Record<number, PlatformConfig> {
        return { ...PLATFORM_CONFIGS };
    }

    /**
     * 获取指定平台配置
     * @param {number} shopType 店铺类型
     * @returns {PlatformConfig | null} 平台配置
     */
    public static getPlatformConfig(shopType: number): PlatformConfig | null {
        return PLATFORM_CONFIGS[shopType] || null;
    }

}

// 创建检测器实例
const detector = new YunLianFangZhouDetectorImpl();


// 延迟自动检测，确保插件完全初始化
function delayedAutoDetection(): void {
    // 等待DOM完全加载
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => {
                performAutoDetection();
            }, 1000); // 延迟1秒
        });
    } else {
        setTimeout(() => {
            performAutoDetection();
        }, 1000); // 延迟1秒
    }
}

function performAutoDetection(): void {
    detector.detectWithExtensionId()
        .then((isInstalled: boolean) => {
            console.log('云链方舟插件检测结果:', isInstalled);
            
            // 触发自定义事件
            const event = new CustomEvent('yunlianfangzhou-detected', {
                detail: detector.getInfo()
            });
            document.dispatchEvent(event);
            
            // 触发内部回调
            (detector as any).triggerDetectedEvent();
        })
        .catch((error: Error) => {
            console.error('自动检测失败:', error);
            // 即使失败也触发事件
            const event = new CustomEvent('yunlianfangzhou-detected', {
                detail: detector.getInfo()
            });
            document.dispatchEvent(event);
            
            // 触发内部回调
            (detector as any).triggerDetectedEvent();
        });
}

// 导出到全局
window.YunLianFangZhou = detector;

// 启动延迟自动检测
delayedAutoDetection();

// 导出类型和实例
export type { 
    YunLianFangZhouDetector, 
    PluginInfo, 
    DetectionResult, 
    CookiesResponse, 
    PlatformConfig, 
    AddShopResult,
    AddShopFunction
};

export { PLATFORM_CONFIGS };
export default detector;
